<template>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
        <div slot="header">
            <!-- 路径导航 -->
            <div slot="header">
                <el-breadcrumb separator="/">
                    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
                    <el-breadcrumb-item>商品管理</el-breadcrumb-item>
                    <el-breadcrumb-item>商品添加</el-breadcrumb-item>
                </el-breadcrumb>
            </div>
        </div>
        <!-- 提示信息 -->
        <el-alert title="添加商品信息" center type="info" show-icon></el-alert>
        <!-- 步骤条 -->
        <el-steps :active="active*1" align-center finish-status="success">
            <el-step title="基本信息"></el-step>
            <el-step title="商品参数"></el-step>
            <el-step title="商品属性"></el-step>
            <el-step title="商品图片"></el-step>
            <el-step title="商品内容"></el-step>
            <el-step title="完成"></el-step>
        </el-steps>
        <!-- 标签页 -->
        <el-form :model="formInfo" ref="form" :rules="formRules" label-width="180px">
            <el-tabs
                tab-position="left"
                v-model="active"
                :before-leave="beforeLeave"
                @tab-click="tabClick"
            >
                <el-tab-pane label="基本信息" name="0">
                    <el-row>
                        <el-col :span="16" :offset="2">
                            <el-form-item label="商品名称" prop="goods_name">
                                <el-input v-model="formInfo.goods_name"></el-input>
                            </el-form-item>
                            <el-form-item label="商品价格" prop="goods_price">
                                <el-input v-model="formInfo.goods_price"></el-input>
                            </el-form-item>
                            <el-form-item label="商品重量" prop="goods_weight">
                                <el-input v-model="formInfo.goods_weight"></el-input>
                            </el-form-item>
                            <el-form-item label="商品数量" prop="goods_number">
                                <el-input v-model="formInfo.goods_number"></el-input>
                            </el-form-item>
                            <el-form-item label="商品分类">
                                <el-cascader
                                    :options="cate_list"
                                    v-model="formInfo.goods_cat"
                                    clearable
                                    :props="{ label:'cat_name',value:'cat_id' }"
                                ></el-cascader>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-tab-pane>
                <el-tab-pane label="商品参数" name="1">
                    <el-row>
                        <el-col :span="16" :offset="2">
                            <el-form-item
                                :label="item.attr_name+':' "
                                v-for="item in manyList"
                                :key="item.attr_id"
                            >
                                <el-checkbox-group v-model="item.attr_vals">
                                    <el-checkbox
                                        :label="val"
                                        v-for="val in item.attr_vals"
                                        :key="val"
                                    ></el-checkbox>
                                </el-checkbox-group>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-tab-pane>
                <el-tab-pane label="商品属性" name="2">
                    <el-row>
                        <el-col :span="16" :offset="2">
                            <el-form-item
                                :label="item.attr_name"
                                v-for="item in onlyList"
                                :key="item.attr_id"
                                label-width="300px"
                            >
                                <el-input v-model="item.attr_vals"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-tab-pane>
                <el-tab-pane label="商品图片" name="3">
                    <el-upload
                        class="upload-demo"
                        :action="$baseURL+'upload'"
                        :headers="headers"
                        :on-preview="handlePreview"
                        :on-remove="handleRemove"
                        :on-success="handleSuccess"
                        list-type="picture"
                    >
                        <el-button size="small" type="primary">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible">
                        <img width="100%" :src="dialogImageUrl" alt />
                    </el-dialog>
                </el-tab-pane>
                <el-tab-pane label="商品内容" name="4">
                    <quill-editor v-model="formInfo.goods_introduce" ref="myQuillEditor"></quill-editor>
                    <el-button type="primary" size="default" @click="addSubmit">添加商品</el-button>
                </el-tab-pane>
            </el-tabs>
        </el-form>
    </el-card>
</template>
<script>
// import "quill/dist/quill.core.css";
// import "quill/dist/quill.snow.css";
// import "quill/dist/quill.bubble.css";
import VueQuillEditor from "vue-quill-editor";
import _ from "lodash";
export default {
    components: {
        VueQuillEditor,
    },
    data() {
        return {
            active: "0",
            formInfo: {
                goods_name: "wuyu",
                goods_cat: [1, 3, 6],
                goods_price: "11",
                goods_number: "0",
                goods_weight: "0",
                goods_introduce: "11",
                pics: [],
                attrs: "",
            },
            formRules: {
                goods_name: [
                    {
                        required: true,
                        message: "请输入商品名称",
                        triggle: "blur",
                    },
                ],

                goods_price: [
                    {
                        required: true,
                        message: "请输入商品价格",
                        triggle: "blur",
                    },
                ],
                goods_number: [
                    {
                        required: true,
                        message: "请输入商品数量",
                        triggle: "blur",
                    },
                ],
                goods_weight: [
                    {
                        required: true,
                        message: "请输入商品重量",
                        triggle: "blur",
                    },
                ],
            },
            cate_list: [], //所有商品的分类
            manyList: [],
            onlyList: [],
            dialogVisible: false,
            headers: {
                Authorization: JSON.parse(sessionStorage.getItem("userinfo"))
                    .token,
            },
            dialogImageUrl: "",
        };
    },
    created() {
        this.getAllcateList();
    },
    computed: {
        cateId() {
            if (this.formInfo.goods_cat.length === 3) {
                return this.formInfo.goods_cat[2];
            } else {
                return null;
            }
        },
    },
    methods: {
        async getAllcateList() {
            let { data: res } = await this.$axios.get("categories");
            if (res.meta.status !== 200)
                return this.$message.error(res.meta.msg);
            this.cate_list = res.data;
        },
        beforeLeave(newval, oldval) {
            if (!this.cateId && oldval == 0) {
                this.$message.error("请输入商品分类");
                return false;
            }
        },
        async tabClick() {
            let sel;
            if (this.active == 1) {
                sel = "many";
            } else if (this.active == 2) {
                sel = "only";
            } else {
                return;
            }

            let { data: res } = await this.$axios.get(
                `categories/${this.cateId}/attributes`,
                {
                    params: {
                        sel,
                    },
                }
            );
            if (res.meta.status !== 200)
                return this.$message.error(res.meta.msg);
            console.log(res.data);
            if (sel === "many") {
                res.data.forEach((item) => {
                    item.attr_vals =
                        item.attr_vals.length == 0
                            ? []
                            : item.attr_vals.split(",");
                });
            }
            this[sel + "List"] = res.data;
        },
        // 图片的预览功能
        handlePreview(file) {
            console.log(file);
            this.dialogVisible = true;
            this.dialogImageUrl = file.response.data.url;
        },
        // 图片的移除事件
        handleRemove(file) {
            console.log(222);
            let index = this.formInfo.pics.findIndex(
                (item) => item.pic === file.response.data.tmp_path
            );
            this.formInfo.pics.splice(index, 1);
        },
        // 图上上传成功
        handleSuccess(res) {
            this.formInfo.pics.push({
                pic: res.data.tmp_path,
            });
        },
        addSubmit() {
            this.$refs.form.validate(async (valid) => {
                if (!valid) return;
                let deepForm = _.cloneDeep(this.formInfo);
                console.log(deepForm);
                deepForm.goods_cat = deepForm.goods_cat.join(",");
                let temp_arr = [];
                this.manyList.forEach((item) => {
                    if (item.attr_vals.length) {
                        temp_arr.push({
                            attr_id: item.attr_id,
                            attr_value: item.attr_vals.join(","),
                        });
                    }
                });
                this.onlyList.forEach((item) => {
                    if (item.attr_vals.length) {
                        temp_arr.push({
                            attr_id: item.attr_id,
                            attr_value: item.attr_vals,
                        });
                    }
                });
                let { data: res } = await this.$axios.post("goods", deepForm);
                if (res.meta.status !== 201)
                    return this.$message.error(res.meta.msg);
                this.$message.success("添加商品成功");
                this.$router.push("/goods");
            });
        },
    },
};
</script>
<style lang="less">
.el-tabs {
    margin-top: 50px;
}
</style>
